<?php
	require_once("Controller/IController.php");
	require_once("view/LoginView.php");
	
	
	class LoginController implements IController{
		private $loginHandler;
		private $loginViewer;
		
		/**
		 * Constructor, creates our private loginHandler- and loginViewer- objects from injected params
		 * @param LoginHandler $loginHandler, LoginView $loginViewer
		 */
		public function __construct(LoginHandler $a_loginHandler){
			$this->loginHandler = $a_loginHandler;
			$this->loginViewer = new LoginView();
		}
		
		public function doControll(){
			$returnString = "";
			$errorStatus = true; // true: no errors, false: Wrong credentials
			$returnArray = array();
			$page = new Page();
			$page->title = "YAIC | Login";
			$user;
			
			//Handle input
			//Tried to logout?
			if($this->loginViewer->triedToLogOut() === true){
				$this->loginViewer->clearCookie();	
				$this->loginHandler->logOut();
				//Redirect to indexpage
				header("Location: index.php?");
			}
			
			//Tried to login?
			if($this->loginViewer->triedToLogIn() === true){
				//Try to login and set cookie, login will retrun boolean
				$user = $this->loginHandler->logIn($this->loginViewer->getUserCredentials());
				if(is_object($user) === true){
					$this->loginViewer->setCookie($user);
				}
				//Else wrong credentials, set error
				else{
					$errorStatus = false;
				}
			}
			
			//Handle output (logged in / logged out)
			if($this->loginHandler->isUserLoggedIn() == true){	
				$page->body .= $this->loginViewer->generateLogoutButton();
				NavigationView::setHeadeLocation("index.php?" . NavigationView::controller . "=" . NavigationView::showUserController . "&". NavigationView::userId. "=" . $this->loginHandler->getLoggedInUser()->userId);
			}
			else{
				$page->body .= $this->loginViewer->generateLoginBox($errorStatus);
			}
			
			return $page;
		}

	}
